package psn.kiko.config.cors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import psn.kiko.config.properties.CORSProperties;

/**
 * 跨域配置
 */
@Component
@Slf4j
public class CORSConfig {
	CORSProperties corsProperties;
	
	@Autowired
	public void setCorsProperties(CORSProperties corsProperties) {
		this.corsProperties = corsProperties;
	}
	
	private CorsConfiguration buildConfiguration( ) {
		log.debug("跨域配置自定义属性：{}" , corsProperties);
		CorsConfiguration corsConfiguration = new CorsConfiguration( );
		//允许的域名
		corsProperties.getAllowedOrigins( ).forEach(corsConfiguration::addAllowedOrigin);
		//允许的请求头
		corsProperties.getAllowedHeaders( ).forEach(corsConfiguration::addAllowedHeader);
		//允许的请求方式
		corsProperties.getAllowedMethods( ).forEach(corsConfiguration::addAllowedMethod);
		return corsConfiguration;
	}
	
	@Bean
	public CorsFilter corsFilter( ) {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource( );
		corsProperties.getPaths( ).forEach(path -> {
			source.registerCorsConfiguration("/**" , buildConfiguration( )); // 对接口配置跨域设置
		});
		return new CorsFilter(source);
	}
}
